package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.DeleteException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studenetMapper;


    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam){

        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        List<Clazz> clazzList = clazzMapper.list();

        //当前时间 > 结课时间：状态未 已结课。当前时间 < 开课时间：状态未 未开班否则，就是 在读中.获取开课时间和结课时间判断
        clazzList.forEach(clazz -> {
            if (clazz.getEndDate().isBefore(ChronoLocalDate.from(LocalDateTime.now()))){
                clazz.setStatus("已结课");
            }else if (clazz.getBeginDate().isAfter(ChronoLocalDate.from(LocalDateTime.now()))){
                clazz.setStatus("未开班");
            }else {
                clazz.setStatus("在读中");
            }
        });

        Page<Clazz> p = (Page<Clazz>) clazzList;//获取总条数和数据

        return new PageResult<Clazz>(p.getTotal(),p.getResult());//返回总条数和数据
    }



    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(Integer id){

        Integer count = clazzMapper.getCountById(id);
        if(count>0){
            throw new DeleteException("对不起, 该班级下有学生, 不能直接删除");
        }else{
            clazzMapper.deleteByIds(id);
            studenetMapper.deleteByClazzIds(id);
        }


    }

    @Override
    public void save(Clazz clazz) {


            //保存员工基本信息
            clazz.setCreateTime(LocalDateTime.now());
            clazz.setUpdateTime(LocalDateTime.now());
            clazzMapper.insert(clazz);//执行完之后，emp对象中id属性值被赋值

    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        //1.根据id修改员工基本信息
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);

        }



    @Override
    public List<Clazz> list() {
       return  clazzMapper.list();
    }


}
